﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace PVMUpdate
{
    class UpdatePVM
    {
        public static class UpdateSettings
        {
            private static Uri UpdateUri;
            private static System.Net.WebClient WebStream;
            private static int iscanud;

            public static void LoadSettings()
            {
                WebStream = new System.Net.WebClient();
                System.Net.WebClient iss = new System.Net.WebClient();
                System.Net.WebHeaderCollection webheader = new System.Net.WebHeaderCollection();
                webheader.Add(System.Net.HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36");
                iss.DownloadFile("https://gitee.com/cai_hongxuan/pntframework-pvm/raw/master/.UPDATEINFO/iscanupdate.txt", "iscan.txt");
                iss.Dispose();
                StreamReader reader = new StreamReader("iscan.txt");
                string cud = reader.ReadLine();
                if (cud == "0")
                {
                    iscanud = 0;
                }
                else if (cud == "1")
                {
                    iscanud = 1;
                    UpdateUri = new Uri(reader.ReadLine(), UriKind.Absolute);
                }
                reader.Close();
            }

            public static bool IfStartUpdate()
            {
                return ((iscanud == 1) ? true : false);
            }

            public static void Update()
            {
                WebStream = new System.Net.WebClient();
                byte[] bytes = WebStream.DownloadData(UpdateUri);
                FileStream fs = new FileStream("Update.zip", FileMode.OpenOrCreate);
                fs.Write(bytes, 0, bytes.Length);
                fs.Close();
                System.IO.Compression.ZipFile.ExtractToDirectory("Update.zip", System.IO.Directory.GetCurrentDirectory());
                File.Delete("Update.zip");

            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            UpdatePVM.UpdateSettings.LoadSettings();
            if(!UpdatePVM.UpdateSettings.IfStartUpdate())
            {
                Console.WriteLine("无需更新程序，因为没有找到合适的更新源！");
                return;
            }

            UpdatePVM.UpdateSettings.Update();
        }
    }
}
